﻿using System;
using System.Linq;
using System.Transactions;
using System.Collections.Generic;
using T.FAS.Runtime.Base.Entity;
using T.FAS.Runtime.Base.Dao;
using T.FAS.Runtime.Base.SGSPI;
using T.ServiceComponent.Kernel.Service;
using T.FAS.Runtime.Base.Common;
using Newtonsoft.Json;
using T.FAS.Runtime.Base.SPI;

namespace T.FAS.Runtime.Base.Service
{
    [SGService]
    public class CodeItemService: ICodeItemService
    {
        private static readonly CodeItemELBDao itemDao = new CodeItemELBDao();
        private readonly Dictionary<string, Func<string, List<CodeItem>>> interrupterCfg =
            new Dictionary<string, Func<string, List<CodeItem>>>
            {
                {"0017",  Get0017Code},
            };

        /// <summary>
        /// 获取码表列表，filter为空查询全部码表，SetId不为空按照SetId过滤
        /// </summary>
        /// <returns></returns>
        [SGService(ServiceID = "FASD-GetCodeItems", 
                    Describtion = "获取码表列表，filter为空查询全部码表，SetId不为空按照SetId过滤", 
                    ServiceType = ServiceType.Retrieve)]
        public  List<CodeItem> GetCodeItems(Dictionary<string, string> filter)
        {
            try
            {
                string setId = null;
                if (filter.ContainsKey("SetId"))
                    setId = filter["SetId"];
                if (TryInterrupter(setId, out var codeItem))
                {
                    return codeItem;
                }
                return itemDao.GetCodeItems(filter)?.OrderBy(o => o.OrderNo).ToList();
            }
            catch (Exception e)
            {

                throw e;
            }
        }
        /// <summary>
        /// 查询码表ByID
        /// </summary>
        /// <param name="NM"></param>
        /// <returns></returns>
        public CodeItem GetCodeItemByID(string NM)
        {
            try
            {
                var tmp = itemDao.GetCodeItemByID(NM);
                if (tmp != null)
                {
                    if (TryInterrupter(tmp.SetId, out var codeItem))
                    {
                        return codeItem?.FirstOrDefault();
                    }
                }
                return tmp;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 保存码表
        /// </summary>
        /// <param name="CodeItem"></param>
        public void SaveCodeItem(CodeItem CodeItem)
        {
            try
            {
                using (var scope = new TransactionScope(TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadCommitted }))
                {
                    var flag = itemDao.CheckCodeItemUnique(new Dictionary<string, string>
                    {
                        {"SetId", CodeItem.SetId },
                        {"Code", CodeItem.Code },
                    });
                    if (flag > 0)
                        throw new Exception($"SetId:{CodeItem.SetId},Code:{CodeItem.Code}已经存在");
                    itemDao.SaveCodeItem(CodeItem);
                    scope.Complete();
                }
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 批量保存码表
        /// </summary>
        /// <param name="codeItems"></param>
        public void SaveCodeItems(List<CodeItem> CodeItems)
        {
            try
            {
                itemDao.SaveCodeItems(CodeItems);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 按主键删除码表
        /// </summary>
        /// <param name="NM"></param>
        public void DeleteCodeItem(string NM)
        {
            try
            {
                itemDao.DeleteCodeItem(NM);
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 按Setid删除码表
        /// </summary>
        /// <param name="SetId"></param>
        public void DeleteCodeItemsBySetId(string SetId)
        {
            try
            {
                itemDao.DeleteCodeItemsBySetId(SetId);
            }
            catch (Exception)
            {

                throw;
            }
        }

        /// <summary>
        /// 拦截配置
        /// </summary>
        /// <param name="setId"></param>
        /// <param name="codeItems"></param>
        /// <returns></returns>
        public bool TryInterrupter(string setId, out List<CodeItem> codeItems)
        {
            codeItems = null;
            if (interrupterCfg.TryGetValue(setId, out var func))
            {
                codeItems = func(setId);
                if (codeItems?.Count > 0)
                    return true;
                else
                    return false;
            }
            return false;
        }

        private static List<CodeItem> Get0017Code(string setId)
        {
            if (string.IsNullOrEmpty(ConfigUtil.Instance.SYSPublicMaskConfigStr)) return null;
            var code0017 = itemDao.GetCodeItemBySetId("0017");
            if (code0017 != null)
            {
                try
                {
                    List<SYSMaskConfig> list = JsonConvert.DeserializeObject<List<SYSMaskConfig>>(ConfigUtil.Instance.SYSPublicMaskConfigStr);
                    int i = 0;
                    List<FASMaskConfig> fasList = new List<FASMaskConfig>();
                    list.ForEach(c => fasList.Add(FASMaskConfig.Mapping(c, i++)));
                    code0017.Description = JsonConvert.SerializeObject(fasList);
                    return new List<CodeItem> { code0017 };
                }
                catch (Exception e)
                {
                    throw new FasException($"FAS-Base-CodeItem-001", $"获取sys系统掩码设置失败");
                }
            }
            throw new FasException($"FAS-Base-CodeItem-001", $"掩码配置setid 0017不存在");
        }
    }
}
